<template>
  <div class="map-container">
    <div id="container" class="map"></div>
    
    <!-- 实时坐标显示 -->
    <div v-if="isTracking" class="coordinate-display">
      <div class="coordinate-title">实时位置 (GCJ-02)</div>
      <div class="coordinate-value">{{ currentPosition }}</div>
      <div class="tracking-count">已记录: {{ tracks_data.length }}/120</div>
    </div>
    
    <!-- 添加标记按钮 -->
    <div class="add-marker-btn" @click="showAddMarkerModal">
      <span class="icon">📍</span>
    </div>
    
    <!-- 菜单按钮 - 现在在右侧 -->
    <div class="menu-btn" @click="$router.push('/mapMenu')">
      <span class="icon">☰</span>
    </div>

    <!-- 位置追踪切换按钮 -->
    <div class="tracking-toggle-btn" @click="togglePositionTracking">
      <span class="icon" :class="{ 'tracking-active': isTracking }">●</span>
    </div>

    <!-- 位置状态提示 -->
    <div v-if="locationStatus" class="location-status" :class="locationStatus.type">
      {{ locationStatus.message }}
    </div>
    
    <!-- 添加标记弹窗 -->
    <div v-if="showModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-header">
          <h3>添加位置标记</h3>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>当前位置坐标 (GCJ-02)</label>
            <input type="text" :value="currentPosition" readonly>
          </div>
          <div class="form-group">
            <label>备注</label>
            <textarea v-model="markNote" placeholder="请输入位置备注"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-cancel" @click="closeModal">取消</button>
          <button class="btn btn-confirm" @click="confirmAddMarker">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiService } from '../utils/http'
import { tools } from '../utils/tools'

export default {
  name: 'Map',
  data() {
    return {
      map: null,
      userMarker: null,
      accuracyCircle: null,
      showModal: false,
      markNote: '',
      currentPosition: '',
      currentLng: 0,
      currentLat: 0,
      locationStatus: null,
      isLocationFromGPS: false,
      // 位置追踪相关数据
      isTracking: false,
      positionWatchId: null,
      updateInterval: null,
      statusTimer: null,
      // 新增：轨迹记录相关数据
      tag: '',
      tracks_data: [],
      // 新增：可视区域标记管理
      visibleMarkers: [], // 存储当前可视区域的标记
      debounceTimer: null // 防抖计时器
    }
  },
  mounted() {
    this.initMap()
  },
  beforeUnmount() {
    // 组件销毁时清理监听器
    this.stopPositionTracking()
    if (this.statusTimer) {
      clearTimeout(this.statusTimer)
    }
    if (this.debounceTimer) {
      clearTimeout(this.debounceTimer)
    }
    
    // 移除地图事件监听
    if (this.map) {
      this.map.off('moveend', this.handleMapMoveEnd)
      this.map.off('zoomend', this.handleMapMoveEnd)
    }
    
    // 清除所有标记
    this.clearVisibleMarkers()
  },
  methods: {
    async initMap() {
      // 先显示加载状态
      this.showLocationStatus('loading', '正在获取位置信息...')
      
      try {
        await this.getCurrentLocation()
      } catch (error) {
        console.error('位置获取失败:', error)
        this.showLocationStatus('error', '获取位置失败，使用默认位置')
        this.initDefaultMap()
      }
    },

    // 切换位置追踪状态
    togglePositionTracking() {
      if (this.isTracking) {
        this.stopPositionTracking()
      } else {
        this.startPositionTracking()
      }
    },

    // 开始位置追踪
    startPositionTracking() {
      if (this.isTracking) return

      this.isTracking = true
      console.log('开始位置追踪，每0.5秒更新一次位置信息')

      // 记录开始时间
      this.tag = this.getCurrentTime()
      this.tracks_data = [] // 清空之前的轨迹数据
      console.log('轨迹记录开始时间:', this.tag)

      // 使用 watchPosition 进行持续位置监听
      const trackingOptions = {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0
      }

      this.positionWatchId = navigator.geolocation.watchPosition(
        (position) => {
          this.handlePositionUpdate(position)
        },
        (error) => {
          console.error('位置追踪错误:', error)
          this.handleTrackingError(error)
        },
        trackingOptions
      )

      // 设置每0.5秒更新一次的定时器作为备份
      this.updateInterval = setInterval(() => {
        this.forcePositionUpdate()
      }, 500)

      this.showLocationStatus('success', '已开启位置追踪', 2000)
    },

    // 停止位置追踪
    stopPositionTracking() {
      if (!this.isTracking) return

      this.isTracking = false
      console.log('停止位置追踪')

      // 如果还有未上传的数据，上传剩余数据
      if (this.tracks_data.length > 0) {
        this.uploadTracksData()
      }

      if (this.positionWatchId) {
        navigator.geolocation.clearWatch(this.positionWatchId)
        this.positionWatchId = null
      }
      
      if (this.updateInterval) {
        clearInterval(this.updateInterval)
        this.updateInterval = null
      }

      this.showLocationStatus('warning', '已停止位置追踪', 2000)
    },

    // 获取当前时间，格式为"2025-11-21 00:07:22"
    getCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 处理位置更新
    handlePositionUpdate(position) {
      const wgsLng = position.coords.longitude
      const wgsLat = position.coords.latitude
      const accuracy = position.coords.accuracy
      
      // 转换为GCJ-02坐标系
      const [gcjLng, gcjLat] = this.transformWGS84ToGCJ02(wgsLng, wgsLat)
      
      // 更新位置数据
      this.currentLng = gcjLng
      this.currentLat = gcjLat
      this.currentPosition = `经度: ${gcjLng.toFixed(6)}, 纬度: ${gcjLat.toFixed(6)} (GCJ-02)`
      this.isLocationFromGPS = true
      
      // 更新地图上的位置标记
      this.updateMapPosition()

      // 记录位置数据到轨迹数组
      this.recordTrackPosition(gcjLat, gcjLng)
    },

    // 记录位置到轨迹数组
    recordTrackPosition(latitude, longitude) {
      // 将位置数据添加到数组
      this.tracks_data.push([latitude, longitude])
      console.log(`记录位置: [${latitude.toFixed(6)}, ${longitude.toFixed(6)}], 总数: ${this.tracks_data.length}`)

      // 检查是否达到120个数据点
      if (this.tracks_data.length >= 120) {
        console.log('达到120个数据点，开始上传轨迹数据')
        this.uploadTracksData()
      }
    },

    // 上传轨迹数据
    async uploadTracksData() {
      if (this.tracks_data.length === 0) {
        console.log('没有轨迹数据需要上传')
        return
      }

      try {
        const requestData = {
          tag: this.tag,
          data: this.tracks_data
        }

        console.log('调用/TracksAdd接口，参数:', requestData)
        
        // 调用接口上传数据
        await this.TracksAdd(requestData)
        
        console.log('轨迹数据上传成功')
        this.showLocationStatus('success', `已上传${this.tracks_data.length}个轨迹点`, 2000)
        
        // 清空数组
        this.tracks_data = []
        
      } catch (error) {
        console.error('轨迹数据上传失败:', error)
        this.showLocationStatus('error', '轨迹数据上传失败', 3000)
      }
    },

    // 模拟TracksAdd接口调用
    TracksAdd(params) {
      const headers = {token: `${tools.getTokenFromCookie()}`}
      const { res, isAuthenticated } = tools.authApiCall(
        () => apiService.post('/TracksAdd', params, { headers }),
        this.$router,
        this.$route
      )
      return res
    },

    // 强制位置更新
    forcePositionUpdate() {
      if (!this.isTracking) return
      
      const singleOptions = {
        enableHighAccuracy: true,
        timeout: 3000,
        maximumAge: 0
      }
      
      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.handlePositionUpdate(position)
        },
        (error) => {
          console.warn('强制位置更新失败:', error)
        },
        singleOptions
      )
    },

    // 处理追踪错误
    handleTrackingError(error) {
      let errorMessage = '位置追踪错误: '
      switch(error.code) {
        case error.PERMISSION_DENIED:
          errorMessage = '位置权限被拒绝，无法进行位置追踪'
          this.stopPositionTracking()
          break
        case error.POSITION_UNAVAILABLE:
          errorMessage = '位置信息不可用，请检查GPS'
          break
        case error.TIMEOUT:
          errorMessage = '位置请求超时'
          break
        default:
          errorMessage = '位置追踪发生未知错误'
      }
      
      this.showLocationStatus('error', errorMessage)
    },

    // 更新地图上的位置
    updateMapPosition() {
      if (!this.map) return
      
      // 更新标记位置
      if (this.userMarker) {
        this.userMarker.setPosition([this.currentLng, this.currentLat])
      }
      
      // 更新精度圆圈
      this.updateAccuracyCircle()
    },

    // 更新精度圆圈
    updateAccuracyCircle() {
      // 移除旧的精度圆圈
      if (this.accuracyCircle) {
        this.map.remove(this.accuracyCircle)
      }
      
      // 添加新的精度圆圈
      if (this.isLocationFromGPS) {
        this.accuracyCircle = new AMap.Circle({
          center: [this.currentLng, this.currentLat],
          radius: 50, // 50米精度圆圈
          strokeColor: '#4CAF50',
          strokeWeight: 2,
          strokeOpacity: 0.5,
          fillColor: '#4CAF50',
          fillOpacity: 0.2,
          map: this.map
        })
      }
    },

    // 显示位置状态提示（支持自动隐藏）
    showLocationStatus(type, message, autoHideDelay = null) {
      // 清除之前的定时器
      if (this.statusTimer) {
        clearTimeout(this.statusTimer)
        this.statusTimer = null
      }
      
      this.locationStatus = { type, message }
      
      // 如果设置了自动隐藏延迟，则设置定时器
      if (autoHideDelay && autoHideDelay > 0) {
        this.statusTimer = setTimeout(() => {
          this.locationStatus = null
          this.statusTimer = null
        }, autoHideDelay)
      }
    },

    // WGS-84 转 GCJ-02 坐标系转换函数
    transformWGS84ToGCJ02(wgsLng, wgsLat) {
      const PI = 3.1415926535897932384626;
      const a = 6378245.0;
      const ee = 0.00669342162296594323;

      function transformLat(x, y) {
        let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
        return ret;
      }

      function transformLon(x, y) {
        let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
      }

      function outOfChina(lng, lat) {
        if (lng < 72.004 || lng > 137.8347) {
          return true;
        }
        if (lat < 0.8293 || lat > 55.8271) {
          return true;
        }
        return false;
      }

      if (outOfChina(wgsLng, wgsLat)) {
        return [wgsLng, wgsLat];
      }

      let dLat = transformLat(wgsLng - 105.0, wgsLat - 35.0);
      let dLng = transformLon(wgsLng - 105.0, wgsLat - 35.0);
      const radLat = wgsLat / 180.0 * PI;
      let magic = Math.sin(radLat);
      magic = 1 - ee * magic * magic;
      const sqrtMagic = Math.sqrt(magic);
      dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
      dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
      const gcjLat = wgsLat + dLat;
      const gcjLng = wgsLng + dLng;

      return [gcjLng, gcjLat];
    },

    async getCurrentLocation() {
      return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
          reject(new Error('浏览器不支持地理定位'))
          return
        }

        // 检查是否在安全上下文中（移动端重要）
        if (!this.isSecureContext()) {
          this.showLocationStatus('warning', '请使用HTTPS或本地环境获取精确位置')
        }

        const options = {
          enableHighAccuracy: true,    // 移动端建议开启高精度
          timeout: 15000,              // 增加超时时间到15秒
          maximumAge: 0                // 不使用缓存位置
        }

        navigator.geolocation.getCurrentPosition(
          (position) => {
            const wgsLng = position.coords.longitude
            const wgsLat = position.coords.latitude
            const accuracy = position.coords.accuracy
            
            // 转换为GCJ-02坐标系
            const [gcjLng, gcjLat] = this.transformWGS84ToGCJ02(wgsLng, wgsLat)
            
            this.currentLng = gcjLng
            this.currentLat = gcjLat
            this.currentPosition = `经度: ${gcjLng.toFixed(6)}, 纬度: ${gcjLat.toFixed(6)} (GCJ-02)`
            this.isLocationFromGPS = true
            
            this.showLocationStatus('success', `位置获取成功 (精度: ${Math.round(accuracy)}米)`, 3000)
            
            this.initializeMap()
            resolve(position)
          },
          (error) => {
            let errorMessage = '位置获取失败: '
            switch(error.code) {
              case error.PERMISSION_DENIED:
                errorMessage = '位置权限被拒绝，请在浏览器设置中允许位置访问'
                break
              case error.POSITION_UNAVAILABLE:
                errorMessage = '位置信息不可用，请检查GPS是否开启'
                break
              case error.TIMEOUT:
                errorMessage = '位置请求超时，请重试'
                break
              default:
                errorMessage = '未知错误，请重试'
            }
            
            this.showLocationStatus('error', errorMessage)
            reject(new Error(errorMessage))
          },
          options
        )
      })
    },

    initializeMap() {
      // 创建地图实例 - 使用GCJ-02坐标
      // 添加限制旋转的配置
      this.map = new AMap.Map('container', {
        zoom: this.isLocationFromGPS ? 15 : 10,
        center: [this.currentLng, this.currentLat],
        viewMode: '2D', // 强制使用2D模式，避免3D旋转
        mapStyle: 'amap://styles/normal',
        // 禁用旋转和倾斜的相关配置
        rotateEnable: false,      // 禁用旋转
        pitchEnable: false,       // 禁用倾斜
        pitch: 0,                // 倾斜角度设为0
        rotation: 0,             // 旋转角度设为0
        // 其他交互控制
        doubleClickZoom: true,   // 允许双击缩放
        dragEnable: true,        // 允许拖拽
        zoomEnable: true,        // 允许缩放
        keyboardEnable: false,   // 禁用键盘操作（避免意外旋转）
        jogEnable: false,        // 禁用拖拽时的缓动效果
        animateEnable: true,     // 允许动画
        touchZoom: true,         // 允许触摸缩放
        scrollWheel: true        // 允许鼠标滚轮缩放
      })
      
      // 进一步确保禁用旋转操作
      this.disableMapRotation()
      
      // 添加用户位置标记
      const markerColor = this.isLocationFromGPS ? 'mark_b' : 'mark_r'
      this.userMarker = new AMap.Marker({
        position: [this.currentLng, this.currentLat],
        icon: `https://webapi.amap.com/theme/v1.3/markers/n/${markerColor}.png`,
        map: this.map,
        title: '您的位置'
      })

      // 添加精度圆圈
      this.updateAccuracyCircle()

      // 新增：添加地图点击事件监听
      this.addMapClickListener()

      // 新增：添加地图移动和缩放监听
      this.addMapMoveEndListener()

      // 初始加载可视区域标记
      this.updateVisibleMarkers()
    },

    // 禁用地图旋转的额外措施
    disableMapRotation() {
      if (!this.map) return
      
      // 监听地图事件，确保不会发生旋转
      this.map.on('rotating', () => {
        // 如果检测到旋转，立即重置为0度
        this.map.setRotation(0)
      })
      
      this.map.on('pitching', () => {
        // 如果检测到倾斜，立即重置为0度
        this.map.setPitch(0)
      })
      
      // 设置地图控件，移除旋转相关控件
      this.map.setStatus({
        rotateEnable: false,
        pitchEnable: false
      })
    },
    
    initDefaultMap() {
      // 天安门坐标已经是GCJ-02坐标系
      this.currentLng = 116.397428
      this.currentLat = 39.90923
      this.currentPosition = `经度: 116.397428, 纬度: 39.90923 (默认位置 GCJ-02)`
      this.isLocationFromGPS = false
      
      // 创建默认地图，同样禁用旋转
      this.map = new AMap.Map('container', {
        zoom: 10,
        center: [this.currentLng, this.currentLat],
        viewMode: '2D', // 强制使用2D模式
        mapStyle: 'amap://styles/normal',
        // 禁用旋转和倾斜
        rotateEnable: false,
        pitchEnable: false,
        pitch: 0,
        rotation: 0,
        // 其他交互控制
        doubleClickZoom: true,
        dragEnable: true,
        zoomEnable: true,
        keyboardEnable: false,
        jogEnable: false,
        animateEnable: true,
        touchZoom: true,
        scrollWheel: true
      })
      
      // 应用额外的旋转限制
      this.disableMapRotation()

      // 添加默认位置标记
      this.userMarker = new AMap.Marker({
        position: [this.currentLng, this.currentLat],
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        map: this.map,
        title: '默认位置 (天安门)'
      })

      // 新增：添加地图点击事件监听
      this.addMapClickListener()

      // 新增：添加地图移动和缩放监听
      this.addMapMoveEndListener()

      // 初始加载可视区域标记
      this.updateVisibleMarkers()
    },

    addMapClickListener() {
      if (!this.map) return
      
      // 监听地图点击事件
      this.map.on('click', (event) => {
        // 获取点击位置的GCJ-02坐标
        const lng = event.lnglat.getLng()
        const lat = event.lnglat.getLat()
        
        // 更新当前坐标
        this.currentLng = lng
        this.currentLat = lat
        this.currentPosition = `经度: ${lng.toFixed(6)}, 纬度: ${lat.toFixed(6)} (GCJ-02)`
        
        // 显示添加标记弹窗
        this.showAddMarkerModal()
        
        console.log(`地图点击坐标: 经度 ${lng.toFixed(6)}, 纬度 ${lat.toFixed(6)}`)
      })
    },

    // 新增：添加地图移动和缩放结束监听
    addMapMoveEndListener() {
      if (!this.map) return

      // 监听地图移动和缩放结束事件
      this.map.on('moveend', this.handleMapMoveEnd)
      this.map.on('zoomend', this.handleMapMoveEnd)
    },

    // 新增：处理地图移动和缩放结束
    handleMapMoveEnd() {
      // 使用防抖，避免频繁调用接口
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer)
      }
      
      this.debounceTimer = setTimeout(() => {
        this.updateVisibleMarkers()
      }, 500) // 500毫秒防抖
    },

    // 新增：更新可视区域标记
    async updateVisibleMarkers() {
      if (!this.map) return

      try {
        // 获取地图可视区域边界
        const bounds = this.map.getBounds()
        const southwest = bounds.getSouthWest() // 左下角
        const northeast = bounds.getNorthEast() // 右上角

        // 构建请求参数
        const params = {
          left_bottom: [southwest.lat, southwest.lng], // 左下角 [纬度, 经度]
          right_top: [northeast.lat, northeast.lng]    // 右上角 [纬度, 经度]
        }

        console.log('获取可视区域坐标:', params)
        
        // 调用接口获取可视区域内的标记
        const response = await this.VisibleAddressQuery(params)
        
        // 清除之前的标记
        this.clearVisibleMarkers()
        
        // 创建新的标记
        if (response.data && Array.isArray(response.data.data)) {
          response.data.data.forEach(item => {
            this.createVisibleMarker(item)
          })
          console.log(`创建了 ${response.data.data.length} 个可视区域标记`)
        }
        
      } catch (error) {
        console.error('获取可视区域标记失败:', error)
      }
    },

    // 新增：清除可视区域标记
    clearVisibleMarkers() {
      this.visibleMarkers.forEach(marker => {
        if (marker && this.map) {
          this.map.remove(marker)
        }
      })
      this.visibleMarkers = []
    },

    // 新增：创建可视区域标记
    createVisibleMarker(item) {
      if (!this.map) return

      // 创建橙色五角星标记
      const marker = new AMap.Marker({
        position: [item.y, item.x], // x是纬度，y是经度
        content: this.createStarMarkerContent(item.mark),
        offset: new AMap.Pixel(-10, -10), // 修改偏移量，让坐标点位于五角星中心
        map: this.map
      })

      this.visibleMarkers.push(marker)
    },

    // 新增：VisibleAddressQuery接口调用
    async VisibleAddressQuery(params) {
      const headers = {token: `${tools.getTokenFromCookie()}`}
      const { res, isAuthenticated } = await tools.authApiCall(
        () => apiService.post('/VisibleAddressQuery', params, { headers }),
        this.$router,
        this.$route
      )
      return res
    },

    isSecureContext() {
      return window.isSecureContext || 
             location.protocol === 'https:' || 
             location.hostname === 'localhost' || 
             location.hostname === '127.0.0.1'
    },
    
    showAddMarkerModal(lng = null, lat = null) {
      // 如果传入了坐标参数，则更新当前坐标
      if (lng !== null && lat !== null) {
        this.currentLng = lng
        this.currentLat = lat
        this.currentPosition = `经度: ${lng.toFixed(6)}, 纬度: ${lat.toFixed(6)} (GCJ-02)`
      }
      this.showModal = true
    },
    
    closeModal() {
      this.showModal = false
      this.markNote = ''
    },
    
    async confirmAddMarker() {
      try {
        const params = {
          longitude: this.currentLng,
          latitude: this.currentLat,
          mark: this.markNote || '未命名位置'
        }
        
        console.log('调用/addSite接口，参数:', params)
        
        await this.addSite(params)
        
        // 创建橙色五角星标记
        const starMarker = new AMap.Marker({
          position: [params.longitude, params.latitude],
          content: this.createStarMarkerContent(params.mark),
          offset: new AMap.Pixel(-10, -10), // 修改偏移量，让坐标点位于五角星中心
          map: this.map
        })
        
        // alert(`已添加标记: ${params.mark}`)
        this.closeModal()
      } catch (error) {
        console.error('添加标记失败:', error)
        alert('添加标记失败，请重试')
      }
    },

    // 创建橙色五角星标记内容
    createStarMarkerContent(markText) {
      // 橙色五角星SVG
      const starSvg = `
        <svg width="20" height="20" viewBox="0 0 20 20">
          <!-- 五角星路径，确保中心点在 (10,10) -->
          <path d="M10 2 L12.5 7.5 L18.5 7.5 L13.5 11.5 L15.5 17.5 L10 14 L4.5 17.5 L6.5 11.5 L1.5 7.5 L7.5 7.5 Z" 
                fill="#FF9800" stroke="#FF5722" stroke-width="0.8"/>
        </svg>
      `
      
      // 创建容器
      const container = document.createElement('div')
      container.style.cssText = `
        position: relative;
        display: flex;
        align-items: center;
        cursor: pointer;
      `
      
      // 添加五角星容器
      const starContainer = document.createElement('div')
      starContainer.style.cssText = `
        position: relative;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
      `
      
      // 添加五角星
      const starDiv = document.createElement('div')
      starDiv.innerHTML = starSvg
      starDiv.style.cssText = `
        display: block;
      `
      
      // 添加文本标签
      const textDiv = document.createElement('div')
      textDiv.textContent = markText
      textDiv.style.cssText = `
        margin-left: 8px;
        background: rgba(255, 255, 255, 0.95);
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        color: #333;
        white-space: nowrap;
        border: 1px solid #FF9800;
        box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        z-index: 5;
        max-width: 150px;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 500;
      `
      
      starContainer.appendChild(starDiv)
      container.appendChild(starContainer)
      container.appendChild(textDiv)
      
      return container
    },
    
    // 模拟API调用
    addSite(params) {
      const headers = {token: `${tools.getTokenFromCookie()}`}
      const { res, isAuthenticated } = tools.authApiCall(
        () => apiService.post('/AddressAdd', {
        mark: params.mark,
        x: params.latitude,
        y: params.longitude
      }, { headers }),
        this.$router,
        this.$route
      )
      return res
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

/* 实时坐标显示 */
.coordinate-display {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 16px;
  z-index: 1000;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #333;
}

.coordinate-title {
  font-weight: 600;
  color: #4CAF50;
}

.coordinate-value {
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.tracking-count {
  font-size: 12px;
  color: #FF9800;
  font-weight: 500;
}

.add-marker-btn {
  position: absolute;
  top: 60px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 20px;
  transition: all 0.3s;
  z-index: 1000;
}

.add-marker-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.menu-btn {
  position: absolute;
  top: 178px;
  right: 20px; /* 修改：从 left: 20px 改为 right: 20px */
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #4CAF50;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
  z-index: 1000;
}

.menu-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

/* 位置追踪切换按钮 */
.tracking-toggle-btn {
  position: absolute;
  top: 120px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 24px;
  transition: all 0.3s;
  z-index: 1000;
  border: 2px solid #333;
}

.tracking-toggle-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.tracking-toggle-btn .icon {
  color: #333;
  transition: color 0.3s;
}

.tracking-toggle-btn .icon.tracking-active {
  color: #f44336;
}

/* 位置状态提示 */
.location-status {
  position: absolute;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  z-index: 1000;
  text-align: center;
  max-width: 80%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.location-status.loading {
  background-color: #2196F3;
  color: white;
}

.location-status.success {
  background-color: #4CAF50;
  color: white;
}

.location-status.warning {
  background-color: #FF9800;
  color: white;
}

.location-status.error {
  background-color: #f44336;
  color: white;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.modal-body {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

input, textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

textarea {
  min-height: 80px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #333;
}

.btn-confirm {
  background-color: #4CAF50;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .coordinate-display {
    padding: 6px 12px;
    font-size: 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 2px;
  }
  
  .coordinate-value {
    font-size: 11px;
  }

  .tracking-count {
    font-size: 11px;
  }
  
  .add-marker-btn, .menu-btn, .tracking-toggle-btn {
    width: 44px;
    height: 44px;
    font-size: 18px;
  }
  
  .add-marker-btn {
    top: 50px;
    right: 15px;
  }
  
  .tracking-toggle-btn {
    top: 104px;
    right: 15px;
  }
  
  .menu-btn {
    top: 158px;
    right: 15px; /* 移动端也保持右侧 */
  }
  
  .location-status {
    top: 50px;
    font-size: 12px;
    padding: 8px 16px;
  }
}
</style>
